<template>
    <main>
      <a href="/">home</a>
        <h1>支付宝/微信支付</h1>
        <form id="payment-form" @submit.prevent="handleSubmit">
      <div>
        <label for="price"><input name="price" id="price">美元</label>
        <p>当前执行汇率</p>
      </div>
      <button id="submit-button">确认金额</button>
    </form>

    <form id="topay" @submit.prevent="handlePay">
      <div id="payment-element"></div>
      <button id="pay-button">支付</button>
    </form>
      <sr-messages :messages="messages" />
    </main>
</template>
<script setup>
  import { ref, onMounted } from "vue";
  import { loadStripe } from "@stripe/stripe-js";
  
  import SrMessages from "./SrMessages.vue";
  
  // const isLoading = ref(false);
  const messages = ref([]);
  let stripe;
  let appearance = {
    theme: 'stripe',
  };
  let elements;
  let paymentElementOptions = {
    layout: "tabs",
  };
  
onMounted(async () => {
const { publishableKey } = await fetch("/api/stripe/config").then((res) => res.json());
stripe = await loadStripe(publishableKey);


});

const handleSubmit = async () => {
  const priceInput = document.querySelector('#price');
  messages.value.push(priceInput.value)
  await fetch('/api/stripe/useAlipay',
      {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            userId: sessionStorage.getItem('id'),
            price: priceInput.value
          }),
        })
        .then(r => r.json())
        .then(data => {
          messages.value.push('支付前')
          // confirmPayment(data.clientSecret)
          const clientSecret = data.clientSecret
          elements = stripe.elements({ appearance, clientSecret });
          const paymentElement = elements.create("payment", paymentElementOptions);
          paymentElement.mount("#payment-element");
        });
        
        
}

const handlePay = async () => {
  
  await stripe.confirmPayment({
    elements,
    confirmParams: {
      // Make sure to change this to your payment completion page
      return_url: window.location.origin + '/return'
    },
  });
}

  
</script>